<template>
  <uni-popup
    ref="popup"
    type="center"
    background-color="#fff"
    @click="closeAndStopRecord"
  >
    <view class="popup-content" @click.stop>
      <view class="record-icon-box">
        <uni-icons
          type="mic-filled"
          size="120"
          :color="info.iconColor"
        ></uni-icons>
      </view>

      <view class="record-time-box">
        <text>{{ info.recordTime }}</text>
      </view>

      <view class="record-btn-box">
        <button v-show="info.recordFlag" @tap="startRecord">开始录音</button>
        <button v-show="!info.recordFlag" @tap="endRecord">停止录音</button>
      </view>
    </view>
  </uni-popup>
</template>

<script setup>
import { FileUploadPublic } from '@/api';
const popup = ref(null);
const RefRecorde = ref(null);
const emit = defineEmits(['recordBack']);

const info = reactive({
  iconColor: '#000',
  voicePath: '',
  recordFlag: true,
  baseTime: 30, // 基础时长30秒
  recordTime: 30,
});
let countdownInterval = null;
let shouldUpload = true; // 是否上传服务器

const recorderManager = uni.getRecorderManager();
const innerAudioContext = uni.createInnerAudioContext();
innerAudioContext.autoplay = true;

const open = () => popup.value.open();
const close = () => popup.value.close();

const startRecord = () => {
  console.log('开始录音');
  info.iconColor = '#f00';
  info.recordFlag = false;
  shouldUpload = true;

  info.recordTime = 30;
  countdownInterval = setInterval(() => {
    if (info.recordTime > 0) {
      info.recordTime--;
    } else {
      endRecord(); // 如果倒计时结束，自动停止录音
    }
  }, 1000);

  recorderManager.start({
    duration: 30 * 1000, // 录音的最大时长，单位 ms，这里设置为30秒
    sampleRate: 16000, // 采样率
  });
};

const endRecord = () => {
  console.log('停止录音');

  info.iconColor = '#000';
  info.recordFlag = true;
  recorderManager.stop();

  clearInterval(countdownInterval);
  info.recordTime = info.baseTime; // 重置倒计时
  close();
};

const closeAndStopRecord = () => {
  shouldUpload = false; // 点击空白处不上传
  endRecord(); // 停止录音
};

onMounted(() => {
  recorderManager.onStop(function (res) {
    console.log('是否上传');
    if (!shouldUpload) {
      console.log('不要上传');
      return;
    }
    console.log('去上传');
    // {"tempFilePath":"_doc/uniapp_temp_1725070720207/recorder/1725070740455.mp3"}
    console.log('recorder stop' + JSON.stringify(res));
    info.voicePath = res.tempFilePath;

    FileUploadPublic({
      filePath: res.tempFilePath,
    })
      .then((res) => {
        console.log(res);
        /*
        {
            "data": "{\"msg\":\"成功\",\"code\":\"0\",\"data\":[{\"docname\":\"1725074889629.mp3\",\"seq\":\"1725076012301\"}]}",
            "statusCode": 200,
            "errMsg": "uploadFile:ok"
        }
        */
        if (res.statusCode === 200) {
          const backData = JSON.parse(res.data);
          if (backData.code === '0') {
            emit('recordBack', backData.data);
          } else {
            uni.showToast({
              title: '录音上传失败',
              icon: 'none',
            });
          }
        } else {
          uni.showToast({
            title: '录音上传失败',
            icon: 'none',
          });
        }
      })
      .catch((err) => {
        console.log('录音 err', err);
        uni.showToast({
          title: '录音上传失败',
          icon: 'none',
        });
      });
  });
});

defineExpose({
  open,
  close,
});
</script>

<style lang="scss" scoped>
.popup-content {
  background-color: #fff;
  border-radius: 20rpx;
  overflow: hidden;
  width: 60%;
  height: auto;
  position: fixed;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);

  .record-icon-box {
    padding-top: 20rpx;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .record-time-box {
    text-align: center;
    font-size: 40rpx;
    color: #333;
  }

  .record-btn-box {
    padding-top: 20rpx;
  }
  button {
    width: 100%;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    background-color: #007aff;
    color: #fff;
    border: none;
    border-radius: 0;
    margin: 0;
    padding: 0;
  }
}
</style>
